package jdbc.preparestatement_;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * @author DCSGO
 * @version 1.0
 * PrepareStatement 小练习
 * 1.使用 PreparedStatement 添加5条数据
 * 2.修改tom的记录，将name改成 king
 * 3.删除一条的记录
 * 4.查询全部记录,并显示在控制台
 */
@SuppressWarnings({"all"})
public class PrepareStatementExercise {
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String Driver = properties.getProperty("Driver");
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        Class.forName(Driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        //1.使用 PreparedStatement 添加5条数据
        String sql = "insert into admin values (?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < 5; i++) {
            preparedStatement.setString(1, "admin_" + i);
            preparedStatement.setString(2, "pwd_" + i);
            preparedStatement.executeUpdate();
        }
        //2.修改tom的记录，将name改成 king
        sql = "update admin set name = 'king' where name = 'tom'";
        preparedStatement.executeUpdate(sql);
        // 3.删除一条的记录
        sql = "delete from admin where `name` = 'admin_2'";
        preparedStatement.executeUpdate(sql);
        // 4.查询全部记录,并显示在控制台
        sql = "select * from admin";
        ResultSet resultSet = preparedStatement.executeQuery(sql);
        while (resultSet.next()) {
            String name = resultSet.getString(1);
            String pwd = resultSet.getString(2);
            System.out.println(name + "\t\t" + pwd);
        }
        preparedStatement.close();
        connection.close();
        /*
         * king		123
         * admin_0		pwd_0
         * admin_1		pwd_1
         * admin_3		pwd_3
         * admin_4		pwd_4
         *
         * 进程已结束，退出代码为 0
         */
    }
}
